const app = getApp()

Page({
  data: {
    repairTypes: [
      { type: '家电维修', priceRange: '100-800' },
      { type: '手机维修', priceRange: '80-500' },
      { type: '电脑维修', priceRange: '100-1000' },
      { type: '平板维修', priceRange: '80-600' },
      { type: '其他', priceRange: '50-1000' }
    ], // 维修类型及价格区间
    repairTypeIndex: null,
    estimatePrice: '',
    totalAmount: '',
    deviceTypes: ['手机', '电脑', '平板', '家电', '其他'],
    deviceTypeIndex: null,
    deviceModel: '',
    problemTypes: ['屏幕维修', '电池更换', '系统问题', '硬件故障', '其他'],
    problemTypeIndex: null,
    description: '',
    location: '',
    contactInfo: '',
    repairType: '预约报修',
    dateValue: '',
    timeValue: '',
    images: [], // 新增：用于存储选择的图片路径
    contactName: '' // 新增：从userInfo获取昵称作为联系人姓名
  },
  onLoad() {
    console.log('报修页面加载')
    // 自动填充用户信息（假设已存储在本地）
    const userInfo = wx.getStorageSync('userInfo') || {};
    console.log('用户信息：', userInfo)
    this.setData({
      contactInfo: userInfo.phone || '',
      location: userInfo.address || '',
      contactName: userInfo.nickname || ''
    });
  },
  onDeviceTypeChange(e) {
    this.setData({
      deviceTypeIndex: e.detail.value
    });
  },
  onDeviceModelInput(e) {
    this.setData({
      deviceModel: e.detail.value
    });
  },
  onProblemTypeChange(e) {
    this.setData({
      problemTypeIndex: e.detail.value
    });
  },
  onDescInput(e) {
    this.setData({
      description: e.detail.value
    });
  },
  onLocationInput(e) {
    this.setData({
      location: e.detail.value
    });
  },
  onContactInput(e) {
    this.setData({
      contactInfo: e.detail.value
    });
  },
  onRepairTypeChange(e) {
    const idx = e.detail.value;
    const priceRange = this.data.repairTypes[idx].priceRange;
    // 取区间最低价并转为数字
    const minPrice = Number(priceRange.split('-')[0]);
    this.setData({
      repairTypeIndex: idx,
      estimatePrice: priceRange,
      totalAmount: minPrice
    });
  },
  onDateChange(e) {
    this.setData({
      dateValue: e.detail.value
    });
  },
  onTimeChange(e) {
    this.setData({
      timeValue: e.detail.value
    });
  },

  // 新增：选择图片
  chooseImage() {
    wx.chooseImage({
      count: 3, // 最多可以选择的图片张数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        this.setData({
          images: this.data.images.concat(tempFilePaths)
        });
      }
    });
  },

  // 新增：删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    let images = this.data.images;
    images.splice(index, 1);
    this.setData({
      images: images
    });
  },

  // 新增：上传图片到后端
  uploadImages() {
    return new Promise((resolve, reject) => {
      const uploadTasks = this.data.images.map(imagePath => {
        return new Promise((uploadResolve, uploadReject) => {
          wx.uploadFile({
            url: `${app.globalData.baseUrl}/api/upload/images`, // 使用全局baseUrl
            filePath: imagePath,
            name: 'file', // 后端接收文件的字段名
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (uploadRes) => {
              if (uploadRes.statusCode === 200) {
                const data = JSON.parse(uploadRes.data);
                uploadResolve(data.url); // 假设后端返回图片URL在data.url中
              } else {
                uploadReject('图片上传失败: ' + uploadRes.statusCode);
              }
            },
            fail: (uploadErr) => {
              uploadReject('图片上传失败: ' + uploadErr.errMsg);
            }
          });
        });
      });

      Promise.all(uploadTasks)
        .then(urls => {
          resolve(urls);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  async submitRepair() {
    const userId = wx.getStorageSync('userId');
    console.log('userId:', userId);
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 表单验证
    if (this.data.repairTypeIndex === null) {
      wx.showToast({
        title: '请选择维修类型',
        icon: 'none'
      });
      return;
    }
    if (this.data.deviceTypeIndex === null) {
      wx.showToast({
        title: '请选择设备类型',
        icon: 'none'
      });
      return;
    }
    if (!this.data.deviceModel) {
      wx.showToast({
        title: '请输入设备型号',
        icon: 'none'
      });
      return;
    }
    if (this.data.problemTypeIndex === null) {
      wx.showToast({
        title: '请选择问题类型',
        icon: 'none'
      });
      return;
    }
    if (!this.data.description) {
      wx.showToast({
        title: '请描述问题',
        icon: 'none'
      });
      return;
    }
    if (!this.data.location) {
      wx.showToast({
        title: '请输入地址',
        icon: 'none'
      });
      return;
    }
    if (!this.data.contactInfo) {
      wx.showToast({
        title: '请输入联系方式',
        icon: 'none'
      });
      return;
    }

    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    try {
      // 处理图片上传
      let imageUrls = [];
      if (this.data.images && this.data.images.length > 0) {
        try {
          imageUrls = await this.uploadImages();
        } catch (error) {
          console.error('图片上传失败:', error);
          wx.hideLoading();
          wx.showToast({
            title: '图片上传失败',
            icon: 'none'
          });
          return;
        }
      }

      // 准备提交数据
      const repairData = {
        userId: userId,
        orderId: 'ORD' + Date.now(), // 生成唯一订单号
        deviceType: this.data.deviceTypes[this.data.deviceTypeIndex],
        deviceModel: this.data.deviceModel,
        problemType: this.data.problemTypes[this.data.problemTypeIndex],
        description: this.data.description,
        location: this.data.location,
        contactInfo: this.data.contactInfo,
        status: 'pending',
        totalAmount: this.data.totalAmount || 0,
        paymentStatus: 'unpaid',
        images: imageUrls.join(','),
        nickname: this.data.contactName || '' // 使用contactName作为nickname
      };

      // 如果有预约时间，添加到请求数据中
      if (this.data.dateValue && this.data.timeValue) {
        repairData.appointmentTime = `${this.data.dateValue}T${this.data.timeValue}:00`;
      }

      // 添加调试日志
      console.log('准备提交的数据:', repairData);
      console.log('请求URL:', `${app.globalData.baseUrl}/api/orders`);
      console.log('Token:', wx.getStorageSync('token'));

      // 发送报修请求
      return new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.baseUrl}/api/orders`,
          method: 'POST',
          data: repairData,
          header: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (res) => {
            console.log('服务器响应:', res); // 添加响应日志
            wx.hideLoading();
            if (res.statusCode === 200 || res.statusCode === 201) {
              wx.showToast({
                title: '报修成功',
                icon: 'success'
              });
              // 延迟返回上一页
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
              resolve(res.data);
            } else {
              wx.showToast({
                title: res.data.message || '提交失败',
                icon: 'none'
              });
              reject(new Error(res.data.message || '提交失败'));
            }
          },
          fail: (error) => {
            wx.hideLoading();
            console.error('提交失败:', error);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            });
            reject(error);
          }
        });
      });
    } catch (error) {
      wx.hideLoading();
      console.error('提交过程出错:', error);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
      throw error;
    }
  }
});